<?php

namespace app\controller\wmapi;

use App\Library\Y;
use app\model\DcdSpecsCans;
use app\model\WaAdminRoles;
use app\model\WaApproveSetting;
use app\model\WaBillCode;
use app\model\WaConfig;
use app\model\WaDepartment;
use app\model\WaSupplier;
use app\model\WaSupplierDomesticLogisticsFees;
use app\model\WaSupplierExamineApprove;
use app\model\WaSupplierInsuranceCompany;
use app\model\WaSupplierRegistrationFee;
use app\model\WaSupplierTransferExportFee;
use App\Service\RedisService;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\SignatureInvalidException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use plugin\admin\app\common\Util;
use plugin\admin\app\controller\Crud;
use plugin\admin\app\model\User;
use support\Request;
use support\Response;
use Tinywan\Jwt\Exception\JwtCacheTokenException;
use Tinywan\Jwt\JwtToken;
use Workerman\Worker;
use app\model\WaAdmins;
use app\model\WaUsersProvider;
use app\model\WpPosts;
use app\model\WaOrders;
use app\model\WaPurchaseOrdersExamineApprove;
use app\model\WaPurchaseContractExamineApprove;
use app\model\WaSalesOrdersExamineApprove;
use app\model\WaSalesContractExamineApprove;
use app\functions;
use Asan\PHPExcel;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tinywan\Validate\Validate;
use App\Service;
use app\model\DcdSeries;


class IndexController extends Crud
{
    public function index(Request $request)
    {

        $rule = WaAdminRoles::all();
        return $rule;
    }

    /**
     * 仪表板
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function dashboard(Request $request): Response
    {
        // 今日新增用户数
        $today_user_count = User::where('created_at', '>', date('Y-m-d') . ' 00:00:00')->count();
        // 7天内新增用户数
        $day7_user_count = User::where('created_at', '>', date('Y-m-d H:i:s', time() - 7 * 24 * 60 * 60))->count();
        // 30天内新增用户数
        $day30_user_count = User::where('created_at', '>', date('Y-m-d H:i:s', time() - 30 * 24 * 60 * 60))->count();

        $argument = $request->all();
        $days = $argument['days'];
        // 全部
        // 昨日
        if ($days == 'default') {
            $start_time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $end_time = time();
        }


        // 昨日
        if ($days == 'yesterday') {
            $start_time = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
            $end_time = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
        }

        // 今日
        if ($days == 'today') {
            $start_time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $end_time = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        }

        // 本周
        if ($days == 'week') {
            $start_time = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y'));
            $end_time = $endLastweek = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7, date('Y'));
        }

        // 本月
        if ($days == 'month') {
            $start_time = mktime(0, 0, 0, date('m'), 1, date('Y'));
            $end_time = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        }

        // 上月
        if ($days == 'lastmonth') {
            $start_time = mktime(0, 0, 0, date('m') - 1, 1, date('Y'));
            $end_time = mktime(23, 59, 59, date('m') - 1, date('t'), date('Y'));
        }
        // 自定义
        if ($days == 'define') {
            $start_time = mktime(0, 0, 0, date('m'), 1, date('Y'));
            $end_time = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        }

        $user_count = WaAdmins::userCount($start_time, $end_time);// 用户总人数
        $provider_count = WaUsersProvider::providerCount($start_time, $end_time);; // 供应商总数 wa_users_
        $posts_count = WpPosts::postsCount($start_time, $end_time);; // 产品总数
        $orders_count = WaOrders::ordersCount($start_time, $end_time); // 销售订单总额  wa_orders
        $purchased_count = WaOrders::ordersCount($start_time, $end_time); // 订单中已购车辆总额


        // 待我审批、我发起的
        $product_count = WaSupplierExamineApprove::postsCount(); // 供应商审批
        $product_count = WaSalesOrdersExamineApprove::postsCount(); // 销售订单审批   wa_sales_order_examine_approve  WaSalesOrdersExamineApprove
        $product_count = WaSalesContractExamineApprove::postsCount(); // 销售合同审批   wa_sales_contract_examine_approve  WaSalesContractExamineApprove
        $product_count = WaPurchaseOrdersExamineApprove::postsCount(); // 采购订单审批  wa_purchase_order_examine_approve WaPurchaseOrdersExamineApprove
        $product_count = WaPurchaseContractExamineApprove::postsCount(); // 采购合同审批   wa_purchase_contract_examine_approve WaPurchaseContractExamineApprove
//                                                                 采购请款审批    wa_purchase_request_examine_approve  WaPurchaseRequestExamineApprove
//        wa_traffic_compulsory_insurance_examine_approve  WaTrafficCompulsoryInsuranceExamineApprove

        //待我跟进
        $product_count = 0; // 产品总数
        //  产品代办
        $product_count = 0; // 产品总数
        //  报价单代办
        $product_count = 0; // 产品总数
        //  报价单代办
        $product_count = 0; // 产品总数
        //  报价单代办
        $product_count = 0; // 产品总数
        //  报价单代办
        $product_count = 0; // 产品总数
        //  销售订单啊代办
        $product_count = 0; // 产品总数
        //  销售合同啊代办
        $product_count = 0; // 产品总数
        //审批动态
        $product_count = 0; // 产品总数
        //公共
        $product_count = 0; // 产品总数


        // mysql版本
        $version = Util::db()->select('select VERSION() as version');
        $mysql_version = $version[0]->version ?? 'unknown';

        $day7_detail = [];
        $now = time();
        for ($i = 0; $i < 7; $i++) {
            $date = date('Y-m-d', $now - 24 * 60 * 60 * $i);
            $day7_detail[substr($date, 5)] = User::where('created_at', '>', "$date 00:00:00")
                ->where('created_at', '<', "$date 23:59:59")->count();
        }
        $res = [
            'code' => 0,
            'data' => [
                'today_user_count' => $today_user_count,
                'day7_user_count' => $day7_user_count,
                'day30_user_count' => $day30_user_count,
                'user_count' => $user_count,
                'php_version' => PHP_VERSION,
                'workerman_version' => Worker::VERSION,
                'webman_version' => Util::getPackageVersion('workerman/webman-framework'),
                'admin_version' => config('plugin.admin.app.version'),
                'mysql_version' => $mysql_version,
                'os' => PHP_OS,
                'day7_detail' => array_reverse($day7_detail),
            ],
            'msg' => '请求成功'
        ];
        return json($res);

    }

    //验证成功
    public static function processVerify()
    {
        $res = [
            'code' => 200,
            'msg' => '验证成功',
            'data' => ''
        ];
        return json_encode($res);
    }

    //成功返回
    public static function successed($data = [], $msg = 'success'): Response
    {
        $res = [
            'code' => 200,
//            'msg' => $msg,
            'msg' => '',
            'data' => json_decode($data),
        ];
        return Response(json_encode($res));
    }

    //失败返回
    public static function errored($data = [], $msg = 'error'): Response
    {
        $res = [
            'code' => 500,
            'msg' => $msg,
            'data' => $data,
        ];
        return Response(json_encode($res));
    }

    //失败返回
    public static function error_by_static($data = [], $msg = 'error')
    {
        $res = [
            'code' => 500,
            'msg' => $msg,
            'data' => $data,
        ];

        return json_encode($res);
    }

    //成功返回
    public static function success_by_static($data = [], $msg = 'error')
    {
        $res = [
            'code' => 200,
            'msg' => $msg,
            'data' => $data,
        ];
        return json_encode($res);
    }


    //301失败返回
    public static function errored301($data = [], $msg = 'success'): Response
    {
        $res = [
            'code' => 301,
            'msg' => $msg,
            'data' => $data,
        ];
        return Response(json_encode($res));
    }

    //401失败返回
    public static function errored401($data = [], $msg = 'error'): Response
    {
        $res = [
            'code' => 401,
            'msg' => $msg,
            'data' => $data,
        ];
        return Response(json_encode($res));
    }

    //501失败返回
    public static function errored501($data = [], $msg = 'success'): Response
    {
        $res = [
            'code' => 501,
            'msg' => $msg,
            'data' => $data,
        ];
        return Response(json_encode($res));
    }


    /**
     * 图片上传-固定
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function upload1(Request $request)
    {
        $param = $request->all();
        // 公共
        $time = time();
        $url_i = '/uploads/images/';
        $url_s = '/public/uploads/images/';
        // 单独文件夹
//        if ($param['type'] == 1){
//            $url_i = '/uploads/images/';
//            $url_s = '/public/uploads/images/';
//        }elseif($param['type'] == 2){
//            $url_i = '/uploads/images/';
//            $url_s = '/public/uploads/images/';
//        }elseif($param['type'] == 3){
//            $url_i = '/uploads/images/';
//            $url_s = '/public/uploads/images/';
//        }elseif($param['type'] == 4){
//            $url_i = '/uploads/images/';
//            $url_s = '/public/uploads/images/';
//        }elseif($param['type'] == 5){
//            $url_i = '/uploads/images/';
//            $url_s = '/public/uploads/images/';
//        }elseif($param['type'] == 6){
//            $url_i = '/uploads/images/';
//            $url_s = '/public/uploads/images/';
//        }elseif($param['type'] == 7){
//            $url_i = '/uploads/images/';
//            $url_s = '/public/uploads/images/';
//        }elseif($param['type'] == 8){
//            $url_i = '/uploads/images/';
//            $url_s = '/public/uploads/images/';
//        }
        $file = $request->file('files');
        if ($file && $file->isValid()) {
            $file->move(public_path() . $url_i . time() . $file->getUploadName());
            $data = $url_s . time() . $file->getUploadName();
            return IndexController::successed(json_encode($data), 'upload success');
        }
        return IndexController::errored('', 'upload error');
    }

    /**
     * 图片上传-按天
     * @param Request $request
     * @return Response|void
     */
    public function upload(Request $request)
    {

        $url_i = '/uploads/images/' . date("Y-m-d") . "/";
        $url_s = '/public/uploads/images/' . date("Y-m-d") . "/"; // 按天生成子目录;
//        $url_pa = '/uploads/images/' . date("Y-m-d") . "/"; // 图片存的路由
        $route = $request->uri(); // 方法
        $path = $request->host(); // 获取路由路径
        if ($path == "wm.webman.com:8787") {
            $path = "http://192.168.110.110";
        } elseif ($path == "192.168.110.110:8787") {
            $path = "http://192.168.110.110";
        } elseif ($path == 'frontforeign.olivenev.com') {
            $path = 'http://adminforeign.olivenev.com';
        }
        // 创建目录
        if (!file_exists($url_s)) {
            mkdir($url_s, 0777, true);
        }
        $file = $request->file('files');
        if ($file && $file->isValid()) {
            $file->move(public_path() . $url_i . time() . $file->getUploadName());
            $data = $path . $url_s . time() . $file->getUploadName();
            move_uploaded_file($file, $url_s . basename($file));
            return IndexController::successed(json_encode($data), 'upload success');
        }
    }


    /**
     * wp图片上传-按天
     * @param Request $request
     * @return Response|void
     */
    public function wpupload(Request $request)
    {

//        $protocol = 'http://';
//        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
//            $protocol = 'https://';
//        }
//        $host = $_SERVER['HTTP_HOST']; // 获取当前域名
//        return ;


        $url_i = '/uploads/images/' . date("Y-m-d") . "/";
        $url_s = public_path() . '/uploads/images/' . date("Y-m-d") . "/"; // 按天生成子目录;
        // 创建目录
        if (!file_exists($url_s)) {
            mkdir($url_s, 0777, true);
        }
        $file = $request->file('files');
        if ($file && $file->isValid()) {
            $file->move(public_path() . $url_i . time() . $file->getUploadName());
            $data = $url_s . time() . $file->getUploadName();
            move_uploaded_file($file, $url_s . basename($file));
            return IndexController::successed(json_encode($data), 'upload success');
        }
    }


    /**
     * 下载指定路径文件
     * @param $file_url
     * @param string $new_name
     */
    // $file_url文件根对路径
    // $new_name文件自定义名称
    public static function download($file_url, $new_name = '')
    {

    }

    /**
     * Note : 生成销售订单编号
     * @return String
     */
    public static function generateOrderSn()
    {
        $year = date('Y');
        if ($year >= 2000) {
            $year = $year - 2000;
        }
        $seconds = date('s');
        $padded_seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT); // 使用str_pad添加0
//        return sprintf('%s%s%s%s%s', str_pad('', '0', STR_PAD_LEFT), $year, date('md'), self::getRandomNum(4), $padded_seconds);
        return sprintf('%s%s%s', str_pad('', '0', STR_PAD_LEFT), $year, date('md'));

    }

    /**
     * Note : 生成其它订单编号
     * @return String
     */
    public static function generateOrderSnOther()
    {
        $year = date('Y');
        if ($year >= 2000) {
            $year = $year - 2000;
        }
        $seconds = date('s');
        $padded_seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT); // 使用str_pad添加0
        return sprintf('%s%s%s%s%s', str_pad('', '0', STR_PAD_LEFT), $year, date('md'), self::getRandomNum(4), $padded_seconds);

    }

    public static function generateOrderContractSn($adminId, $other_id)
    {
        $admin_id = $adminId->id;  // 业务员编号
        $count = strlen($admin_id . $other_id);
        $num = 2 + 8 - $count;
        $sn = sprintf('%s%s%s', str_pad($num, '0', STR_PAD_LEFT), date('m'), self::getRandomNum($num));
        $year = date('Y');
        $year = substr($year, 2);
        $sn = $year . $sn . $admin_id . $other_id;
        return $sn;
//        return sprintf('%s%s%s', str_pad($num, '0', STR_PAD_LEFT), date('m'), self::getRandomNum($num));
    }

    /**
     * 生成数字随机数
     */
    public static function getRandomNum($len)
    {
        $chars = "0123456789QWERTYUIOPASDFGHJKLZXCVBNM";
        for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }

    /**
     * 生成数字随机数
     */
    public static function getRandomNums($len)
    {
        $chars = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
        for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }

    /**
     * Note : 生成产品编号
     * @return String
     */
    public static function productSn()
    {
        return sprintf('%s%s%s', str_pad(6, '0', STR_PAD_LEFT), date('His'), self::getRandomNum(6));
    }

    /**
     * 验证类型
     */
    public static function validateType()
    {
//        格式验证类
//格式验证类的验证规则如果在使用静态方法调用的时候需要加上is（以number验证为例，需要使用 isNumber()）。
//
//require
//验证某个字段必须，例如：
//
//'name'=>'require'
//'num'=>'number' 是否为纯数字
//'num'=>'integer' 是否为整数
//'num'=>'float' 是否为浮点数字
//'num'=>'boolean'是否为布尔值
//'email'=>'email'是否为email地址
//'info'=>'array'是否为数组
//'accept'=>'accepted'是否为为 yes, on
//'date'=>'date'是否为有效的日期
//'name'=>'alpha'是否为纯字母
//'name'=>'alphaNum'是否为字母和数字
//'name'=>'alphaDash'是否为字母和数字，下划线_及破折号-
//'name'=>'chs'只能是汉字
//'name'=>'chsAlpha'只能是汉字、字母
//'name'=>'chsAlphaNum'只能是汉字、字母和数字
//'name'=>'chsDash'只能是汉字、字母、数字和下划线_及破折号-
//'name'=>'cntrl'只能是控制字符（换行、缩进、空格
//'name'=>'graph'只能是可打印字符（空格除外）
//'name'=>'print'只能是可打印字符（包括空格
//'name'=>'lower'只能是小写字符
//'name'=>'upper'只能是大写字符
//'name'=>'space'只能是空白字符（包括缩进，垂直制表符，换行符，回车和换页字符
//'name'=>'xdigit'只能是十六进制字符串
//'host'=>'activeUrl'是否为有效的域名或者IP
//'url'=>'url'是否为有效的URL地址
//'ip'=>'ip'否为有效的IP地址
//'create_time'=>'dateFormat:y-m-d'是否为指定格式的日期
//'mobile'=>'mobile'否为有效的手机
//'id_card'=>'idCard'否为有效的身份证格式
//'mac'=>'macAddr'否为有效的MAC地址
//zip
//验证某个字段的值是否为有效的邮政编码，例如：
//
//'zip'=>'zip'
//长度和区间验证类
//'num'=>'in:1,2,3'是否在某个范围
//'num'=>'notIn:1,2,3'值不在某个范围
//'num'=>'between:1,10'是否在某个区间
//'num'=>'notBetween:1,10'值不在某个范围
//'name'=>'length:4,25'长度是否在某个范围
//'name'=>'length:4'指定长度
//'name'=>'max:25'值的最大长度
//'name'=>'min:5'值的最小长度
//'begin_time' => 'after:2016-3-18',是否在某个日期之后
//'end_time'   => 'before:2016-10-01',是否在某个日期之前
//'expire_time'   => 'expire:2016-2-1,2016-10-01',是否在某个有效日期之内
//'name'   => 'allowIp:114.45.4.55',是否在某个范围
//'name'   => 'denyIp:114.45.4.55',是否禁止访问
//'repassword'=>'require|confirm:password'是否和另外一个字段的值一致
//'password'=>'require|confirm'进行字段比较是否一致
//'name'=>'require|different:account'是否和另外一个字段的值不一致
//'score'=>'eq:100'否等于某个值
//'num'=>'=:100'
//'num'=>'same:100'
//'score'=>'egt:60'否大于等于某个值
//'num'=>'>=:100'
//'score'=>'gt:60'是否大于某个值
//'num'=>'>:100'
//'score'=>'elt:100'否小于等于某个值
//'num'=>'<=:100'
//'score'=>'lt:100'
//'num'=>'<:100'
//'price'=>'lt:market_price'验证对比其他字段大小（数值大小对比）
//'price'=>'<:market_price'
//
//
//'zip'	=>	'regex:zip',上传验证
//file验证是否是一个上传文件
//image:width,height,type验证是否是一个图像文件
//
//fileExt:允许的文件后缀 验证上传文件后缀
//fileMime:允许的文件类型 验证上传文件类型
//fileSize:允许的文件字节大小 验证上传文件大小
//token:表单令牌名称 表单令牌验证
//unique:table,field,except,pk 验证当前请求的字段值是否为唯一的
//// 表示验证name字段的值是否在user表（不包含前缀）中唯一
//'name'   => 'unique:user',
//// 验证其他字段
//'name'   => 'unique:user,account',
//// 排除某个主键值
//'name'   => 'unique:user,account,10',
//// 指定某个主键值排除
//'name'   => 'unique:user,account,10,user_id',
//如果需要对复杂的条件验证唯一，可以使用下面的方式：
//// 多个字段验证唯一验证条件
//'name'   => 'unique:user,status^account',
//// 复杂验证条件
//'name'   => 'unique:user,status=1&account='.$data['account'],
//requireIf:field,value
//验证某个字段的值等于某个值的时候必须，例如：
//
//// 当account的值等于1的时候 password必须
//'password'=>'requireIf:account,1'
//requireWith:field
//验证某个字段有值的时候必须，例如：
//
//// 当account有值的时候password字段必须
//'password'=>'requireWith:account'
//requireWithout:field
//验证某个字段没有值的时候必须，例如：
//
//// mobile和phone必须输入一个
//'mobile' => 'requireWithout:phone',
//'phone'  => 'requireWithout:mobile'
//requireCallback:callable
//验证当某个callable为真的时候字段必须，例如：
//
//// 使用check_require方法检查是否需要验证age字段必须
//'age'=>'requireCallback:check_require|number'
//用于检查是否需要验证的方法支持两个参数，第一个参数是当前字段的值，第二个参数则是所有的数据。
//
//function check_require($value, $data){
//    if(empty($data['birthday'])){
//        return true;
//    }
//}
//只有check_require函数返回true的时候age字段是必须的，并且会进行后续的其它验证。

    }


    /**
     * 美元-人民币汇率
     */
    public function financeRate()
    {
        $config = WaConfig::find(['name' => 'financeRate']);
        $config = json_decode($config);
        if (!$config) {
            return IndexController::errored('', '获取汇率失败');
        }
//        if ($config->end_time) {
//            $times = intval(strtotime($config->end_time));
//            if ($times > time()) {
//                return IndexController::successed(json_encode($config), '');
//            }
//        }

        $find = WaConfig::find(['name' => 'financeRate']);
        $find = json_decode($find);
        if ($find) {
            if ($find->updated_at) {
                $updated_at = strtotime($find->updated_at);
                // 获取今天的开始时间
                $startTime = strtotime(date('Y-m-d'));
                $endtTime = strtotime(date('Y-m-d H:i:s'), time());
                if ($startTime < $updated_at && $updated_at < $endtTime) {
                    $config = WaConfig::find(['name' => 'financeRate']);
                    $config = json_decode($config);
                    if (!$config) {
                        return IndexController::errored('', '获取汇率失败');
                    }
                    return IndexController::successed(json_encode($config), '');
                } else {
                    //        header("Content-type:text/html;charset=utf-8");
//                    $url = "https://api.exchangerate-api.com/v4/latest/USD";// 离岸 线下不能访问
                    $url = "https://api.tanshuapi.com/api/exchange/v1/index?key=93a380b222fc4b3614288a4b9d526df5&from=USD&to=CNH&money=1";// 离岸
//                    $url = "https://api.tanshuapi.com/api/exchange/v1/index?key=93a380b222fc4b3614288a4b9d526df5&from=CNY&to=CNH&money=1";// 离岸
                    $output = self::http_curl($url);
                    if ($output) {
                        $output = json_decode($output, true);
//                        var_dump($output);
//                        $output = $output['rates']['CNY'];// 汇率值
                    }
//        $urls = "https://sapi.k780.com/?app=finance.rate&scur=USD&tcur=CNY&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4"; // 限制次数
                    $usd_urls = "https://api.tanshuapi.com/api/exchange/v1/index?key=93a380b222fc4b3614288a4b9d526df5&from=USD&to=CNY&money=1";// 美-人
                    $eur_urls = "https://api.tanshuapi.com/api/exchange/v1/index?key=93a380b222fc4b3614288a4b9d526df5&from=EUR&to=CNY&money=1";// 欧-人
                    $cny_urls = "https://api.tanshuapi.com/api/exchange/v1/index?key=93a380b222fc4b3614288a4b9d526df5&from=CNY&to=CNY&money=1";// 人-人
                    $usd_eur_urls = "https://api.tanshuapi.com/api/exchange/v1/index?key=93a380b222fc4b3614288a4b9d526df5&from=USD&to=EUR&money=1";// 美-欧
                    $eur_usd_urls = "https://api.tanshuapi.com/api/exchange/v1/index?key=93a380b222fc4b3614288a4b9d526df5&from=EUR&to=USD&money=1";// 欧-美
                    $usd_outputs = self::http_curl($usd_urls);
                    if ($usd_outputs) {
                        $usd_outputs = json_decode($usd_outputs, true);//
                    }


                    $eur_outputs = self::http_curl($eur_urls);
                    if ($eur_outputs) {
                        $eur_outputs = json_decode($eur_outputs, true);//
                    }

//                    $cny_outputs = self::http_curl($cny_urls);
//                    if ($cny_outputs) {
//                        $cny_outputs = json_decode($cny_outputs, true);//
//                    }


                    $usd_eur_outputs = self::http_curl($usd_eur_urls);
                    if ($eur_outputs) {
                        $usd_eur_outputs = json_decode($usd_eur_outputs, true);//
                    }

                    $eur_usd_outputs = self::http_curl($eur_usd_urls);
                    if ($eur_usd_outputs) {
                        $eur_usd_outputs = json_decode($eur_usd_outputs, true);//
                    }

                    $days = 60 * 60 * 24; // 一天
                    $times = intval(time()) + $days;
                    $data = date('Y-m-d H:i:s', $times);
                    $up = WaConfig::updated(['name' => 'financeRate'], ['value' => $output, 'remark' => json_encode($usd_outputs) . json_encode($usd_outputs), 'updated_at' => dateTime(), 'end_time' => $data,
                        'usd_rate' => $usd_outputs['data']['exchange'],
                        'eur_rate' => $eur_outputs['data']['exchange'],
                        'cny_rate' => 1,
                        'usd_eur_rate' => $usd_eur_outputs['data']['exchange'],
                        'eur_usd_rate' => $eur_usd_outputs['data']['exchange'],
                    ]);
//        $up = WaConfig::updated(['name' => 'financeRate'], ['value' => $output, 'remark' => json_encode($outputs), 'updated_at' => dateTime(), 'end_time' => $data, 'rate' => 7.19]);
                    if (!$up) {
                        return IndexController::errored($up, '更新汇率失败');
                    }
                    $config = WaConfig::find(['name' => 'financeRate']);
                    $config = json_decode($config);
                    if (!$config) {
                        return IndexController::errored('', '获取汇率失败');
                    }
                }
            }
        } else {
            return IndexController::errored('', '获取汇率失败');

        }


        return IndexController::successed(json_encode($config), '');
    }


    /**
     * http请求
     * @param type $url
     * @param type $type
     * @param type $arr
     * @return type
     */
    public static function http_curl($url, $type = 'get', $arr = '')
    {

        if ($arr) {
            $o = "";
            foreach ($arr as $k => $v) {
                $o .= "$k=" . urlencode($v) . "&";
            }
            $arr = substr($o, 0, -1);
        }

        $ch = curl_init();

        $user_agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36";
        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
        curl_setopt($ch, CURLOPT_URL, $url); //设置访问的地址
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //获取的信息返回
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        }
        $output = curl_exec($ch); //采集
        if (curl_error($ch)) {
            return curl_error($ch);
        }
        return $output;
    }


    /**下级部门人员 - 权限
     * @param $adminId
     * @return array
     */
    public static function nextDepartmentMembers($adminId)
    {
        // 是部门主管
        $ids = [];
        if ($adminId->is_principal == 1) {
            array_push($ids, $adminId->id);
            // 数据权限 1 默认全部  2 只看自己
            if ($adminId->data_permission == 1) {
                // 下一级部门有哪些
                $next_department_ids = WaDepartment::all(['id'], [['pid', '=', $adminId->department_id]]);
                $next_department_ids = json_decode($next_department_ids);
                if ($next_department_ids) {
                    foreach ($next_department_ids as $kd) {
                        $next_departments_admin_ids = WaAdmins::all(['*'], [['department_id', '=', $kd->id]]);
                        if ($next_departments_admin_ids) {
                            $next_departments_admin_ids = json_decode($next_departments_admin_ids);
                            foreach ($next_departments_admin_ids as $ke)
                                array_push($ids, $ke->id);
                        }
                    }
                } else {
                    // 没有下一级就把当前部门的
                    $this_departments_admin_ids = WaAdmins::all(['*'], [['department_id', '=', $adminId->department_id]]);
                    $this_departments_admin_ids = json_decode($this_departments_admin_ids);

                    if ($this_departments_admin_ids) {
                        foreach ($this_departments_admin_ids as $key) {
                            array_push($ids, $key->id);
                        }
                    }
                }
            }
        } else {
            array_push($ids, $adminId->id);
        }
        return $ids;
    }


    /**
     * 修改供应商状态 - 公共
     * @param $supplier_type
     * @param $supplier_id
     * @return false|string
     */
    public static function supplierStatusUpCommon($supplier_type, $supplier_id, $supplier_up_data)
    {

        $supplier_up_where = [];
        $supplier_up_where [] = ['id', '=', $supplier_id];
        if ($supplier_type == 1) {
            $supplier_status_up = WaSupplier::updated($supplier_up_where, $supplier_up_data); // 审批驳回
        } elseif ($supplier_type == 2) {
            $supplier_status_up = WaSupplierRegistrationFee::updated($supplier_up_where, $supplier_up_data);
        } elseif ($supplier_type == 3) {
            $supplier_status_up = WaSupplierTransferExportFee::updated($supplier_up_where, $supplier_up_data);
        } elseif ($supplier_type == 4) {
            $supplier_status_up = WaSupplierInsuranceCompany::updated($supplier_up_where, $supplier_up_data);
        } elseif ($supplier_type == 5) {
            $supplier_status_up = WaSupplierDomesticLogisticsFees::updated($supplier_up_where, $supplier_up_data);
        } elseif ($supplier_type == 6) {
            $supplier_status_up = WaSupplierDomesticLogisticsFees::updated($supplier_up_where, $supplier_up_data);
        }
        if (!$supplier_status_up) {
//            $supplier_status_up = json_encode($supplier_status_up);
            return '供应商状态修改失败' . $supplier_status_up;
        }
        return 'true';
    }


    /**
     * 修改供应商详情- 公共
     * @param $supplier_type
     * @param $supplier_id
     * @return false|string
     */
    public static function supplierDetailCommon($supplier_type, $supplier_id)
    {
        $supplier_find_where = [];
        $supplier_find_where [] = ['id', '=', $supplier_id];
        if ($supplier_type == 1) {
            $supplier_detail = WaSupplier::find($supplier_find_where);
        } elseif ($supplier_type == 2) {
            $supplier_detail = WaSupplierRegistrationFee::find($supplier_find_where);
        } elseif ($supplier_type == 3) {
            $supplier_detail = WaSupplierTransferExportFee::find($supplier_find_where);
        } elseif ($supplier_type == 4) {
            $supplier_detail = WaSupplierInsuranceCompany::find($supplier_find_where);
        } elseif ($supplier_type == 5) {
            $supplier_detail = WaSupplierDomesticLogisticsFees::find($supplier_find_where);
        } elseif ($supplier_type == 6) {
            $supplier_detail = WaSupplierDomesticLogisticsFees::find($supplier_find_where);
        }

        return $supplier_detail;
    }

    /**
     * 获取供应商类型名字- 公共
     * @param $supplier_type
     * @param $supplier_id
     * @return false|string
     */
    public static function supplierTypeNameCommon($supplier_type)
    {

        if ($supplier_type == 1) {
            $supplier_type_name = '车辆供应商';
        } elseif ($supplier_type == 2) {
            $supplier_type_name = '上牌供应商';
        } elseif ($supplier_type == 3) {
            $supplier_type_name = '国际货运代理';
        } elseif ($supplier_type == 4) {
            $supplier_type_name = '保险供应商';
        } elseif ($supplier_type == 5) {
            $supplier_type_name = '国内物流供应商';
        } elseif ($supplier_type == 6) {
            $supplier_type_name = '车辆检测供应商';
        } else {
            $supplier_type_name = '暂无此类供应商' . 'type 为' . $supplier_type;

        }
        return $supplier_type_name;
    }

    /**
     * 人民币类型
     * @param $supplier_type
     * @param $supplier_id
     * @return false|string
     */
    public static function currencyNameCommon($currency)
    {
        if ($currency){
            $currency = intval($currency);
        }

        // 货币类型   1 人民币 2 美元 3 欧元
        if ($currency == 1) {
            $currency_name = '人民币';
        } elseif ($currency == 2) {
            $currency_name = '美元';
        } elseif ($currency == 3) {
            $currency_name = '欧元';
        } else {
            $currency_name = '暂无此币种' . $currency;
        }

        return $currency_name;
    }


    /**
     * 账单结算状态名字
     *    1 未结清 2 结款中 3 已结清
     */
    public static function billStatusName($settlement_sratus)
    {
        if ($settlement_sratus == 1) {
            $month_bill_status_name = '未结清';
        } elseif ($settlement_sratus == 2) {
            $month_bill_status_name = '结款中';
        } elseif ($settlement_sratus == 3) {
            $month_bill_status_name = '已结清';
        }
        return $month_bill_status_name;
    }

    /**
     * 销售订单状态名称
     * @param $status
     * @return string
     */
    public static function saleOrderStatusName($status)
    {
        // 订单状态 0 草稿 1 待核验   2 审批中   3 待签署销售合同   4 待支付定金  5 订单采购中 6 待支付余款 7 待发货 8待收货 9 已完成 10 已作废 11 删除
        if ($status == 0) {
            $status_name = '草稿';
        } elseif ($status == 1) {
            $status_name = '待核验';
        } elseif ($status == 2) {
            $status_name = '审批中';
        } elseif ($status == 3) {
            $status_name = '待生成销售合同';
        } elseif ($status == 4) {
            $status_name = '待支付定金';
        } elseif ($status == 5) {
            $status_name = '订单采购中';
        } elseif ($status == 6) {
            $status_name = '待支付余款';
        } elseif ($status == 7) {
            $status_name = '待发货';
        } elseif ($status == 8) {
            $status_name = '待收货';
        } elseif ($status == 9) {
            $status_name = '已完成';
        } elseif ($status == 10) {
            $status_name = '已作废';
        } elseif ($status == 11) {
            $status_name = '删除';
        } elseif ($status == 12) {
            $status_name = '财务确认到账';
        } elseif ($status == 13) {
            $status_name = '待报关';
        } elseif ($status == 16) {
            $status_name = '待财务确认余款到账';
        } elseif ($status == 17) {
            $status_name = '待客户确认签署';
        } elseif ($status == 18) {
            $status_name = '审批驳回';
        } elseif ($status == 19) {
            $status_name = '出口跟单中';
        } elseif ($status == 20) {
            $status_name = '定金到账异常';
        } elseif ($status == 21) {
            $status_name = '尾款到账异常';
        } else {
            $status_name = '';
        }
        return $status_name;
    }


    /**
     * 采购订单状态名称
     * @param $status
     * @return string
     */
    public static function purchaseOrderStatusName($purchase_orders_status)
    {
        if ($purchase_orders_status == 0) {
            $purchase_orders_status_name = '草稿';
        } elseif ($purchase_orders_status == 1) {
            $purchase_orders_status_name = '审批中';
        } elseif ($purchase_orders_status == 2) {
            $purchase_orders_status_name = '待签署采购合同';
        } elseif ($purchase_orders_status == 3) {
            $purchase_orders_status_name = '待支付定金';
        } elseif ($purchase_orders_status == 5) {
            $purchase_orders_status_name = '待配车';
        } elseif ($purchase_orders_status == 6) {
            $purchase_orders_status_name = '已完成';
        } elseif ($purchase_orders_status == 7) {
            $purchase_orders_status_name = '已作废';
        } elseif ($purchase_orders_status == 9) {
            $purchase_orders_status_name = '审批驳回';
        } elseif ($purchase_orders_status == 10) {
            $purchase_orders_status_name = '审批通过';
        } elseif ($purchase_orders_status == 11) {
            $purchase_orders_status_name = '待支付尾款';
        } else {
            $purchase_orders_status_name = '暂无此状态';
        }
        return $purchase_orders_status_name;
    }

    /**
     * 车辆状态名称
     */
    public static function vehicleStatusName($status)
    {
        if ($status == 1) {
            $status_name = '集库待发运';
        } elseif ($status == 2) {
            $status_name = '待验车入库';
        } elseif ($status == 3) {
            $status_name = '已入库待上牌';
        } elseif ($status == 4) {
            $status_name = '已上牌待开二手';
        } elseif ($status == 5) {
            $status_name = '已开票待转移出';
        } elseif ($status == 6) {
            $status_name = '已转移待注销';
        } elseif ($status == 7) {
            $status_name = '已注销待退保';
        } elseif ($status == 8) {
            $status_name = '已退保待集港发运';
        } elseif ($status == 9) {
            $status_name = '已订舱待报关';
        } elseif ($status == 10) {
            $status_name = '已报关(待装运)';
        } elseif ($status == 11) {
            $status_name = '已装运(待提单释放)';
        } elseif ($status == 12) {
            $status_name = '已提单释放(待结关)';
        } elseif ($status == 13) {
            $status_name = '已结关(待退税)';
        } elseif ($status == 14) {
            $status_name = '已退税(完成车务)';
        } elseif ($status == 20) {
            $status_name = '已完成车务';
        } else {
            $status_name = '';
        }
        return $status_name;
    }

    /**
     * 交货条件
     * 1 FAS 2 FOB 3 CIF 4 CIP
     * @param $condition
     * @return string
     */
    public static function conditionName($condition)
    {

        if ($condition == 1) {
            $condition_name = 'FCA';
        } elseif ($condition == 2) {
            $condition_name = 'FOB';
        } elseif ($condition == 3) {
            $condition_name = 'CIF';
        } elseif ($condition == 4) {
            $condition_name = 'CIP';
        } elseif ($condition == 5) {
            $condition_name = 'EXW';
        } else {
            $condition_name = '';
        }

        return $condition_name;
    }

    /**
     * 订单款项类目
     */
    public function orderBillCategory(Request $request)
    {
        $condition = [];
        $condition [] = ['pid', '!=', 0];
        $res = WaBillCode::all($condition);
        if ($res) {
//           $res = json_decode($res);
//           foreach ($res as $ke){
//               $children_condition =  [];
//               $children_condition [] = ['pid','=',$ke->id];
//               $children_data = WaBillCode::all($children_condition);
//               if ($children_data){
//                   $ke->children_data = json_decode($children_data);
//               }else{
//                   $ke->children_data = [];
//               }
//           }
//           $res = json_encode($res);
        }
        return IndexController::successed($res, '订单款项类目');
    }


    /**
     *  记录错误日志的方法
     * @param \Exception $e
     * @param $action
     */
    public static function logError($action, $data, $adminId, $exception)
    {

        // 获取当前操作方法名称
//        $methodName = $this->getCurrentMethodName();
        // 定义日志存储路径
        $logPath = '/logs/' . date("Y-m-d") . "/"; // 请替换为实际的日志路径
        // 获取当前日期
        $date = date('Y-m-d');

        // 构建日志文件夹路径
        $dateDir = public_path() . $logPath . 'Error' . '/';

        // 检查文件夹是否存在，如果不存在则创建
        if (!is_dir($dateDir)) {
            mkdir($dateDir, 0777, true); // 递归创建方法日志文件夹
        }

        // 构建日志文件路径
        $logFile = $dateDir . $action . 'error.log';

        // 获取异常信息
        if ($exception) {
            // 获取异常信息
            $errorMessage = "[" . date('Y-m-d H:i:s') . "] " . $exception . "\n\n";
//            $errorMessage = "[" . date('Y-m-d H:i:s') . "] " . $exception->getMessage() . "\n" . $exception->getTraceAsString() . "\n\n";

//            // 将异常信息写入日志文件
//            file_put_contents($logFile, $errorMessage, FILE_APPEND);
        } else {
            $errorMessage = '';
        }

        if ($data) {
            $data = json_encode($data);
        }
        $datas = [
            'action' => $action, // 操作的方法
            'adminId' => $adminId->nickname, //入参数据
            'time' => date('Y-m-d H:i:s', time()), //入参数据
            'data' => $data, //入参数据
        ];


        // 将报错信息写入日志文件
//        file_put_contents($logFile, json_encode($datas), FILE_APPEND);
        file_put_contents($logFile, $datas, FILE_APPEND);
        file_put_contents($logFile, $errorMessage, FILE_APPEND);
    }



    /**
     *  记录错误日志的方法
     * @param \Exception $e
     * @param $action
     */
    public static function logErrorNew($action, $data)
    {

        // 获取当前操作方法名称
//        $methodName = $this->getCurrentMethodName();
        // 定义日志存储路径
        $logPath = '/logs/' . date("Y-m-d") . "/"; // 请替换为实际的日志路径
        // 获取当前日期
        $date = date('Y-m-d');

        // 构建日志文件夹路径
        $dateDir = public_path() . $logPath . 'Error' . '/';

        // 检查文件夹是否存在，如果不存在则创建
        if (!is_dir($dateDir)) {
            mkdir($dateDir, 0777, true); // 递归创建方法日志文件夹
        }

        // 构建日志文件路径
        $logFile = $dateDir . $action . 'error.log';

        // 将报错信息写入日志文件
//        file_put_contents($logFile, $action, FILE_APPEND);
//        file_put_contents($logFile, dateTime(), FILE_APPEND);
//        file_put_contents($logFile, $data, FILE_APPEND);
        file_put_contents($logFile, $action . PHP_EOL, FILE_APPEND);
        file_put_contents($logFile, date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
        file_put_contents($logFile, $data , FILE_APPEND);

    }


    /**
     *  记录正确日志的方法
     * @param \Exception $e
     * @param $action
     */
    public static function logSuccessed($action, $data, $adminId)
    {

        // 获取当前操作方法名称
//        $methodName = $this->getCurrentMethodName();
        // 定义日志存储路径
        $logPath = '/logs/' . date("Y-m-d") . "/"; // 请替换为实际的日志路径
        // 获取当前日期
        $date = date('Y-m-d');

        // 构建日志文件夹路径
        $dateDir = public_path() . $logPath . 'Successe' . '/';

        // 检查文件夹是否存在，如果不存在则创建
        if (!is_dir($dateDir)) {
            mkdir($dateDir, 0777, true); // 递归创建方法日志文件夹
        }

        // 构建日志文件路径
        $logFile = $dateDir . $action . 'successe.log';

        if ($data) {
            $data = json_encode($data);
        }
        $datas = [
            'action' => $action, // 操作的方法
            'adminId' => $adminId->nickname, //入参数据
            'time' => date('Y-m-d H:i:s', time()), //入参数据
            'data' => $data, //入参数据
        ];
        // 将正确信息写入日志文件
//        file_put_contents($logFile, json_encode($datas), FILE_APPEND);
        file_put_contents($logFile, $datas, FILE_APPEND);
    }

    public static function logSuccessedtest($action, $data, $adminId)
    {

        // 获取当前操作方法名称
//        $methodName = $this->getCurrentMethodName();
        // 定义日志存储路径
        $logPath = '/logs/' . date("Y-m-d") . "/"; // 请替换为实际的日志路径
        // 获取当前日期
        $date = date('Y-m-d');

        // 构建日志文件夹路径
        $dateDir = public_path() . $logPath . 'Successe' . '/';

        // 检查文件夹是否存在，如果不存在则创建
        if (!is_dir($dateDir)) {
            mkdir($dateDir, 0777, true); // 递归创建方法日志文件夹
        }

        // 构建日志文件路径
        $logFile = $dateDir . $action . 'successe.log';


        $datas = [
            'action' => $action, // 操作的方法
            'adminId' => $adminId->nickname, //入参数据
            'time' => date('Y-m-d H:i:s', time()), //入参数据
            'data' => $data, //入参数据
        ];
        // 将正确信息写入日志文件
        file_put_contents($logFile, $data, FILE_APPEND);
    }

    /**
     * 判断是否是英文
     * @param $string
     * @return bool
     */
    public static function isEnglish($string)
    {
        // 正则表达式匹配英文字符（包括大小写字母）、数字、空格和一些常见标点符号
        $pattern = '/[a-zA-Z0-9\s\p{P}]+$/u';

        // 使用 preg_match 函数进行匹配
        if (preg_match($pattern, $string)) {
            return true;
        } else {
            return false;
        }
    }


    public static function firstLetter($string)
    {
        if (empty($string)) {
            return $string; // 如果字符串为空，直接返回
        }

        // 获取字符串的首字母
        $firstLetter = substr($string, 0, 1);

        // 将首字母转换为大写
        $capitalizedFirstLetter = strtoupper($firstLetter);

        // 返回大写后的首字母（这里只返回首字母，如果需要整个字符串且仅首字母大写，请看下文）
        return $capitalizedFirstLetter;
    }


    public static function testChild()
    {
        $sa = 1 + 2 * 3 / 0;
        return $sa;
    }

    // 测试
    public function test(Request $request)
    {
        $adminId = json_decode(adminId($request));
        $data = [
            'name' => 1,
            'name2' => 2,
            'name3' => 3,
            'name4' => 4,
        ];
        IndexController::logSuccessed('44444423rfdsfsdfsd', $data, $adminId);
        \support\Db::beginTransaction();
        try {
            $sa = IndexController::testChild();

            return $sa;

        } catch (\Exception $exception) {
//            throw new \Exception("Something went wrong in the static method.");
            // 处理异常的代码
//            echo '捕获到异常: ',  $exception->getMessage(), "\n";
            return strtotime(date('H:i:s', time()));

        }

        return strtotime(date('H:i:s', time()));

        return strtotime(date('H:i:s', time()));
        //
//        try {
//
//        } catch (\PDOException $exception) {
//            echo $exception;
//        } finally {
//
//        }

//        $param = $request->all();
//        $rule = [
//            'name' => 'require|max:25',
//            'id' => 'require|number|between:1,120',
//            'email' => 'require|email',
//            'ary_data' => 'require',
//        ];
//        $message = [
//            'name.require' => '名称必须填写',
//            'name.max' => '名称最多不能超过25个字符',
//            'age.require' => '年龄必须填写',
//            'age.number' => '年龄必须是数字',
//            'age.between' => '年龄只能在1-120之间',
//            'email.require' => '邮箱必须填写',
//            'email.email' => '邮箱格式错误'
//        ];
//
//        $validate = \Tinywan\Validate\Facade\Validate::rule($rule);
//        $data = [
//            'name' => $param['name'],
//            'email' => $param['email'],
//            'id' => $param['id'],
//            'ary_data' => $param['ary_data'],
//        ];
//        if (!$validate->check($data)) {
//            return $validate->getError();
//        }
////        $res =  process($request);
        return 12312312;
        $year = date('Y');
        if ($year >= 2000) {
            $year = $year - 2000;
        }
        $seconds = date('s');
        $padded_seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT); // 使用str_pad添加0
        return sprintf('%s%s%s%s%s', str_pad('', '0', STR_PAD_LEFT), $year, date('md'), self::getRandomNum(4), $padded_seconds);
//        $res = $year;
//        return json_encode($res);
    }


    // 测试文森 飞书
    public function testW(Request $request)
    {
        $param = $request->all();

        $url = $param['url'];
        $output = self::http_curl($url);
//        if ($output) {
//            $output = json_decode($output, true);
//            var_dump($output);
//
//        }
//        return Response(json_encode($output));

        $res = [
            'code' => 200,
//            'msg' => $msg,
            'msg' => '',
            'data' => $output,
        ];
        return Response(json_encode($res));


    }


    public function testIp(Request $request)
    {


        $param = $request->all();
        $adminId = json_decode(adminId($request));


// 传统 for 循环
        for ($i = 114; $i < 150; $i++) {
            var_dump($i);
            $url = "http://192.168.110." . $i . ":8080/#/dashboard?username=test&password=123456";
//        $url = "https://oapi.dingtalk.com/gettoken?corpid= . $CorpId . &corpsecret=". $appSecret;


//        $url = "https://oapi.dingtalk.com/gettoken?appkey=" . urlencode($appKey) . "&appsecret=" . urlencode($appSecret);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            // 设置连接超时（建议 5 秒）
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
            $response = curl_exec($ch);
            if ($response) {
                return IndexController::successed(json_encode($response), '获取登入信息');
            }
            curl_close($ch);

        }

        return IndexController::successed('', '');

    }

    /**
     * 账单类型名称
     * @param $k
     */
    public static function accountingInformationTypeName($k){
        if ($k->type== 1){
            $k->type_name = '定金';
        }elseif($k->type== 2){
            $k->type_name = '尾款';

        }elseif($k->type== 3){
            $k->type_name = '定金退款';

        }elseif($k->type== 4){
            $k->type_name = '尾款退款';

        }elseif($k->type== 5){
            $k->type_name = ' 客户违约金';

        }elseif($k->type== 6){
            $k->type_name = ' 赔付金';

        }else{
            $k->type_name = '暂无';
        }
        return $k;
    }

    /**
     * 账单状态
     * @param $k
     */
    public static function accountingInformationStatus($k){
        PublicCommentController::账单状态;
        if ($k->type== 1){
            $k->type_name = '待财务确认到账';
        }elseif($k->type== 2){
            $k->type_name = '财务确认到账';

        }elseif($k->type== 3){
            $k->type_name = '到账异常';

        }elseif($k->type== 4){
            $k->type_name = '作废';

        }else{
            $k->type_name = '暂无';
        }
        return $k;
    }


    /**
     * 账单分配状态
     * @param $k
     */
    public static function accountingInformationAllocationStatus($k){
        PublicCommentController::账单分配状态;
        if ($k->type== 1){
            $k->type_name = '待分配';
        }elseif($k->type== 2){
            $k->type_name = '已经足额分配';
        }elseif($k->type== 3){
            $k->type_name = '未足额分配';

        }else{
            $k->type_name = '暂无';
        }
        return $k;
    }
    /**
     *  记录错误日志的方法
     * @param \Exception $e
     * @param $action
     */
    public static function logErrorNew1($action, $data)
    {

        // 获取当前操作方法名称
//        $methodName = $this->getCurrentMethodName();
        // 定义日志存储路径
        $logPath = '/logs/' . date("Y-m-d") . "/"; // 请替换为实际的日志路径
        // 获取当前日期
        $date = date('Y-m-d');

        // 构建日志文件夹路径
        $dateDir = public_path() . $logPath . 'Error' . '/';

        // 检查文件夹是否存在，如果不存在则创建
        if (!is_dir($dateDir)) {
            mkdir($dateDir, 0777, true); // 递归创建方法日志文件夹
        }

        // 构建日志文件路径
        $logFile = $dateDir . $action . 'error.log';

        // 将报错信息写入日志文件
//        file_put_contents($logFile, $action, FILE_APPEND);
//        file_put_contents($logFile, dateTime(), FILE_APPEND);
//        file_put_contents($logFile, $data, FILE_APPEND);
        file_put_contents($logFile, $action . PHP_EOL, FILE_APPEND);
        file_put_contents($logFile, date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
        file_put_contents($logFile, $data , FILE_APPEND);

    }


    /**
     * 百度翻译Api
     * @param Request $request
     * @return string
     */
    public function baiduTranslate(Request $request) {
        $param = $request->all();
        $appid = '20250703002396590'; // 替换为你的App ID
        $secretKey = 'VoTQXV7Lre_avIPgxIpt'; // 替换为你的Secret Key
        $query = $param['text'] ?? null; // 使用null合并运算符处理未定义的'text'键


        if (!$query) {
            return response()->json(['error' => 'Text parameter is missing'], 400);
        }
        $url = 'https://fanyi-api.baidu.com/api/trans/vip/translate';
        $params = [
            'q' => $query,
            'appid' => $appid,
            'salt' => time(),
            'from' => 'zh', // 源语言，例如中文是zh
            'to' => 'en',  // 目标语言，例如英文是en
        ];
//        $output = self::http_curl($url);
        $params['sign'] = IndexController::buildSign($params, $secretKey);
        $ret = IndexController::requestGet($url, $params);

        // 检查返回结果中的错误代码
        if (isset($ret['error_code'])) {
            return response()->json([
                'error' => 'Translation failed',
                'error_code' => $ret['error_code'],
                'error_msg' => $ret['error_msg'] ?? 'Unknown error'
            ], 500);
        }
        return $ret['trans_result'][0]['dst'] ?? '';
    }

    public static function requestGet($url, $params) {


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 建议设置为true以验证SSL证书
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // 建议设置为true以验证SSL证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);    // 建议设置为2以验证主机名

        $result = curl_exec($ch);

        if (curl_errno($ch)) {
            return 'Curl error: ' . curl_error($ch);
        }

        curl_close($ch);

        $response = json_decode($result, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return 'JSON decode error: ' . json_last_error_msg();

        }

        return $response;
    }

    public static function buildSign($params, $secretKey) {
        ksort($params); // 按照字典序排序参数
        $baseStr = '';
        foreach ($params as $key => $value) {
            $baseStr .= "{$key}={$value}&";
        }
        $baseStr .= "appsecret={$secretKey}"; // 添加密钥以获得签名
        return md5(urlencode($baseStr)); // 使用md5获得摘要并返回结果
    }


}
